# -*- coding: utf-8 -*-


import  wx
import  os
import sys
import  wx.wizard as wiz
#import  images
import  encodings.mbcs
import  codecs
from encodings import gbk
from encodings import utf_8
from encodings import latin_1
from encodings import utf_16_le
import wx.grid

import selector    # select file
import xlsgrid     #show excel
import mappicker #mapping picker
import colmapping  # new map
import newcolumns  # new columns
import doit        # doit

import about

import traceback

#import db
import logtextctrl as logtc

import wizdata
import wizpages

import income

import ipatch


import validator

assertMode = wx.PYAPP_ASSERT_DIALOG

LOG_TEXTCTRL = 30001
"""
class Password(wx.Panel):
    def __init__(self,parent):
        #panel = wx.Panel(self, -1)
        wx.Panel.__init__(self, parent, -1)
        basicLabel = wx.StaticText(self, -1, "Basic Control:")
        basicText = wx.TextCtrl(self, -1, "I've entered some text!", size=(175, -1))
        basicText.SetInsertionPoint(0)
        pwdLabel = wx.StaticText(self, -1, "Password:")
        pwdText = wx.TextCtrl(self, -1, "password", size=(175, -1),  style=wx.TE_PASSWORD)
        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
        self.SetSizer(sizer)
"""
#----------------------------------------------------------------------


class ImportWizard(wiz.Wizard):
    def __init__(self, parent, id, title, style):
        wiz.Wizard.__init__(self, parent, -1, title,style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER)
        self.forward = self.FindWindowById(wx.ID_FORWARD)
        self.backward = self.FindWindowById(wx.ID_BACKWARD)
        
        self.Bind(wx.EVT_BUTTON, self.OnForward, self.forward)
        self.Bind(wx.EVT_BUTTON, self.OnBack, self.backward)

        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnWizPageChanged)
        self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnWizPageChanging)
        self.Bind(wiz.EVT_WIZARD_CANCEL, self.OnWizCancel)
        self.Bind(wiz.EVT_WIZARD_FINISHED, self.OnWizFinished) 

        self.log = logtc.LogTextCtrl()        
        
   

    def OnWizPageChanged(self, evt):
        if evt.GetDirection():
            dir = "forward"
        else:
            dir = "backward"
        page = evt.GetPage()
        wizid = evt.GetId()
        wizard = self.FindWindowById(wizid)
        #wizard.GetCurrentPage()

        #self.log.write("OnWizPageChanged: %s, %s\n" % (dir, page.__class__))
        #wizard.SetPageSize((500,600))
        #wizard.FitToPage(page)        
        nextButton = wizard.FindWindowById(wx.ID_FORWARD)
        #nextButton.Enable(False)
        if wizard.HasNextPage(page):
            nextButton.SetLabel(u"下一步")
        else:
            nextButton.SetLabel(u"完成")
        evt.Skip()

    def OnWizPageChanging(self, evt):
        
        data = wizdata.WizData()
        
        if evt.GetDirection():
            dir = "forward"
        else:
            dir = "backward"

        page = evt.GetPage()
            #self.xlspath = page.GetFilePath()
            
        pages = wizpages.WizPages()
        next = page.GetNext()
        if page == pages.page1:
            
            
            
            next.updateView()             # update the view
        elif page == pages.page3:
            #print "page3"
            if pages.built == None:
                next.BuildPanel()
                pages.built = 1
            else:
                next.DestroyChildren()
                next.BuildPanel()
        elif page == pages.page4:
            #print len(data.newcol)
            if len(data.newcol) > 0:
                if pages.newbuild == None:  # not built yet and need to be built
                    next.Build()
                    pages.newbuild = 1
                else:
                    next.DestroyChildren()
                    next.Build()
            else:
                #pages.page5.DestroyChildren()
                
                page.SetNext(pages.page6)
                pages.page6.SetPrev(page)
                if pages.page6.built:
                    pass
                else:
                    pages.page6.BuildPanel()    
                #pass

        elif page == pages.page5:
            #print "page3"
            if pages.built == None:
                next.BuildPanel()
                pages.built = 1
            else:
                next.DestroyChildren()
                next.BuildPanel()


        self.log.write(u"页面: %s, %s\n" % (dir, page.__class__))
        evt.Skip()

    def OnWizCancel(self, evt):
        page = evt.GetPage()
        self.log.write(u"取消导入\n")

        # Show how to prevent cancelling of the wizard.  The
        # other events can be Veto'd too.
        #if page is self.page1:
        #    pass
            #wx.MessageBox("Cancelling on the first page has been prevented.", "Sorry")
            #evt.Veto()
        evt.Skip()
        
    def OnWizFinished(self, evt):
        self.log.write("OnWizFinished\n")
        evt.Skip()

        
    def OnForward(self, event):
        data = wizdata.WizData()
        data.dir = 1        
        event.Skip()

    def OnBack(self, event):
        data = wizdata.WizData()
        data.dir = -1
        event.Skip()
            


class ColoredPanel(wx.Window):
    def __init__(self, parent):
        wx.Window.__init__(self, parent, -1, style = wx.SIMPLE_BORDER)
        #self.SetBackgroundColour(color)
        


class MsgPanel(wx.Notebook):
    def __init__(self,parent):
        wx.Notebook.__init__(self, parent, -1, size=(21,21),
                         #style=
                         #wx.NB_TOP # | wx.NB_MULTILINE
                         #wx.NB_BOTTOM
                         #wx.NB_LEFT
                         #wx.NB_RIGHT
                         )
        self.log = logtc.LogTextCtrl()

        win = self.makeColorPanel()
        self.multiText = wx.TextCtrl(win, LOG_TEXTCTRL,
               u"程序启动\n",
               size=(400, 200), style=wx.TE_MULTILINE)
        
        self.multiText.SetInsertionPoint(1)
        self.AddPage(win, u"日志")        
        win2 = self.makeColorPanel()
        self.AddPage(win2, u"当前指令")
        #self.DeletePage(0)
        
        #self.Bind(wx.EVT_BUTTON, self.OnRunDynamicWizard, b)

    def makeColorPanel(self):
        p = wx.Panel(self, -1)
        win = ColoredPanel(p)
        p.win = win

        

        def OnCPSize(evt, win=win):
            win.SetSize(evt.GetSize())

        p.Bind(wx.EVT_SIZE, OnCPSize)
        return p


    def OnRunDynamicWizard(self,evt):
        self.Begin()
        evt.Skip()

    def Begin(self):
        
        # Create the wizard and the pages
        #wizard = wx.PreWizard()
        #wizard.SetExtraStyle(wx.WIZARD_EX_HELPBUTTON)
        #wizard.Create(self, self.ID_wiz, "Simple Wizard",
        #              images.getWizTest1Bitmap())
        #wizard = wiz.Wizard(self, -1, u"数据导入向导", images.getWizTest1Bitmap())
        
        
        #wizard = wiz.Wizard(self, -1, u"数据导入向导", style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER) #
        wizard = ImportWizard(self, -1, u"数据导入向导", style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER) #
        
        #wizard.statusbar = wizard.CreateStatusBar()
        filep = selector.SelectorPage(wizard, u"选择文件")
        #page2 = SkipNextPage(wizard, u"公司及期间")
        excel = xlsgrid.GridPage(wizard, u"期间") #TitledPage1
        
        
        
        oldmapping = mappicker.MapPicker(wizard, u"选择映射") #TitledPage4        
        

        
        
        mapping = colmapping.MappingPage(wizard, u"建立映射")
        
        
        #page4 = UseAltBitmapPage(wizard, u"处理并完成")
        newcols = newcolumns.NewColumnsPage(wizard, u"新项") #TitledPage3
        dopage = doit.DonePage(wizard, u"完成") #TitledPage3
        
        
        
        pages = wizpages.WizPages()
        pages.page1 = filep
        pages.page2 = excel
        pages.page3 = oldmapping
        pages.page4 = mapping
        pages.page5 = newcols
        pages.page6 = dopage
        
        self.filep = filep

        filep.SetNext(excel) 
        
        excel.SetPrev(filep)        
        excel.SetNext(oldmapping)
        
        oldmapping.SetPrev(excel)
        oldmapping.SetNext(mapping)
        
        mapping.SetPrev(oldmapping)
        mapping.SetNext(newcols)

        newcols.SetPrev(mapping)
        newcols.SetNext(dopage)

        dopage.SetPrev(newcols)
        #done.SetNext(oldmapping)
        
        

        wizard.FitToPage(filep)
        
        #wizard.SetPageSize((800,600))

        backButton = wizard.FindWindowById(wx.ID_BACKWARD)
        backButton.SetLabel(u"上一步")

        cancelButton = wizard.FindWindowById(wx.ID_CANCEL)
        cancelButton.SetLabel(u"取消")
        
        nextButton = wizard.FindWindowById(wx.ID_FORWARD)
        nextButton.Enable(False)
        
        wizard.RunWizard(filep)
        """
        if wizard.RunWizard(filep):
            print "ok"
            pass
            #wx.MessageBox(u"向导成功结束", u"成功")
        else:
            print "not"
            pass
            #wx.MessageBox(u"向导取消", u"取消")
        """
#----------------------------------------------------------------------

class IncomeFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "", size=(800, 800),style = wx.DEFAULT_FRAME_STYLE) 
        #wizard = wiz.Wizard(self, -1, u"数据导入向导",style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
        
        page1 = income.IncomeInfo(self)

class RunApp(wx.App):
    def __init__(self):
        wx.App.__init__(self, redirect=False)

    def OnInit(self):
        wx.Log_SetActiveTarget(wx.LogStderr())
        self.log = logtc.LogTextCtrl()
        self.SetAssertMode(assertMode)

        frame = wx.Frame(None, -1, u"数据处理", pos=(50,50), size=(200,100),
                        style=wx.DEFAULT_FRAME_STYLE)
        self.myframe = frame
        frame.CreateStatusBar()
        
        
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        item = menu.Append(-1, u"退出(&X)", u"退出")
        self.Bind(wx.EVT_MENU, self.OnExitApp, item)
        item1 = menu.Append(-1, u"导入工资表(&D)", u"导入工资表")
        self.Bind(wx.EVT_MENU, self.OnDoit, item1)

        menu1 = wx.Menu()
        item3 = menu1.Append(-1, u"退出(&X)", u"退出")
        self.Bind(wx.EVT_MENU, self.OnExitApp, item3)
        item4 = menu1.Append(-1, u"导入工资表(&D)", u"导入工资表")
        self.Bind(wx.EVT_MENU, self.OnDoit, item4)

        item5 = menu1.Append(-1, u"查看工资信息(&V)", u"查看工资信息")
        self.Bind(wx.EVT_MENU, self.OnQuery, item5)


        menuBar.Append(menu, u"文件(&F)")
        menuBar.Append(menu1, u"工具(&T)")
        
        menu2 = wx.Menu()
        item6 = menu2.Append(-1, u"帮助(&H)", u"帮助")
        self.Bind(wx.EVT_MENU, self.OnHelp, item6)

        item7 = menu2.Append(-1, u"关于(&B)", u"关于")
        self.Bind(wx.EVT_MENU, self.OnAbout, item7)

        menuBar.Append(menu2, u"帮助(&H)")

        ns = {}
        ns['wx'] = wx
        ns['app'] = self
        ns['frame'] = frame
        
        frame.SetMenuBar(menuBar)
        frame.Show(True)
        
        #frame.Bind(wx.EVT_CLOSE, self.OnCloseFrame)

        #win = runTest(frame, frame, Log())

        tb = frame.CreateToolBar( wx.TB_HORIZONTAL
                                 | wx.NO_BORDER
                                 | wx.TB_FLAT
                                 | wx.TB_TEXT
                                 )
        tsize = (16,16)
        new_bmp =  wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, tsize)
        open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, tsize)
        copy_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR, tsize)
        paste_bmp= wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR, tsize)
        
        
        tb.AddSimpleTool(10, new_bmp, "New", u"新建")
        tb.AddSimpleTool(20, open_bmp, "Open", u"打开")
        tb.AddSeparator()
        tb.AddSimpleTool(30, copy_bmp, "Copy", "Copy")
        tb.AddSimpleTool(40, paste_bmp, "Paste", "Paste")
        tb.AddSeparator()
        
        
        self.Bind(wx.EVT_TOOL, self.OnToolClick, id=20)
        """
        cbID = wx.NewId()
        tb.AddControl(
            wx.ComboBox(
                tb, cbID, "", choices=["", "This", "is a", "wxComboBox"],
                size=(150,-1), style=wx.CB_DROPDOWN
                ))
        """
        tb.Realize()
        
        self.win = MsgPanel(frame)

        self.Bind(wx.EVT_SIZE, self.OnSize)

        # a window will be returned if the demo does not create
        # its own top-level window
        if self.win:
            # so set the frame to a good size for showing stuff
            frame.SetSize((640, 480))
            self.win.SetFocus()
            self.window = self.win
            ns['win'] = self.win
            frect = frame.GetRect()

        else:
            # It was probably a dialog or something that is already
            # gone, so we're done.
            frame.Destroy()
            return True
        
        
        self.SetTopWindow(frame)
        self.frame = frame
        #wx.Log_SetActiveTarget(wx.LogStderr())
        #wx.Log_SetTraceMask(wx.TraceMessages)   
        return True
        
    def OnToolClick(self, event):
        #tb = self.GetToolBar()
        self.win.Begin()
        
        
    def OnSize(self, evt):
        size = self.win.GetSize()
        self.mysize = size
        """
        selfsize = self.win.GetSize()
        if selfsize[0] > 100:
            selfsize[0] = 100
        if selfsize[1] > 100:
            selfsize[1] = 100        
        
        
        self.myframe.SetSize(selfsize)
        """
        
        size = (size[0]-16, size[1])
        self.win.multiText.SetSize(size)
        
        """
                Traceback (most recent call last):
          File "vpipe.py", line 527, in OnSize
            self.win.multiText.SetSize(size)
          File "C:\Python24\lib\site-packages\wx-2.6-msw-unicode\wx\_core.py", line 13540, in __getattr__
            raise PyDeadObjectError(self.attrStr % self._name)
        """
        
        
        evt.Skip()
        #if self.win.GetAutoLayout():
        #self.win.Layout()
        
    def OnExitApp(self, evt):
        self.frame.Close(True)

    def OnDoit(self,evt):
        self.win.Begin()
        evt.Skip()
        
    def OnHelp(self,evt):
        helpfile ="vpipe.chm"
        os.startfile(helpfile)  # for windows ?
        evt.Skip()
        
    def OnAbout(self,event):
        dialog = about.About(self.myframe)
        dialog.ShowModal()
        dialog.Destroy()
        event.Skip()
        
    def OnQuery(self,evt):
        #self.win.Begin()
        #fr = IncomeFrame(self)
        #fr.Show()
        
        frame = wx.Frame(None, -1, u"工资数据", pos=(50,50), size=(800,800),
            style=wx.DEFAULT_FRAME_STYLE)

        
        page1 = income.IncomeInfo(frame)
        frame.Show()
        evt.Skip()
        
    def OnCloseFrame(self, evt):
        self.frame.Close(True)
        #if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"):
        #self.window.ShutdownDemo()
        evt.Skip()
        




def main(params = None):
    if params is None:
        params = [""]
    
    if len(sys.argv) > 1:
        params = sys.argv[1:]
    
    # Create single instance semaphore
    single_instance_checker = wx.SingleInstanceChecker("vpipe" + wx.GetUserId())

    if single_instance_checker.IsAnotherRunning():
        # Send  torrent info to abc single instance
        #ClientPassParam(params[0])
        pass
    else:
        vpath = os.path.abspath(os.path.dirname(sys.argv[0]))
        print vpath
        os.chdir(vpath)
        app = RunApp()
        app.MainLoop()

if __name__ == "__main__":
    main()

